package com.itcam.article.service.impl;

import com.itcam.article.domain.Comment;
import com.itcam.article.repository.CommentRepository;
import com.itcam.article.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author : Cammy.Wu
 * Description : 
 */

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    /**
     * 保存一个评论
     * @param comment
     */
    @Override
    public void saveComment(Comment comment) {
        commentRepository.save(comment);
    }

    /**
     * 更新评论
     * @param comment
     */
    @Override
    public void updateComment(Comment comment) {
        commentRepository.save(comment);
    }

    /**
     * 根据id删除评论
     * @param id
     */
    @Override
    public void deleteCommentById(String id) {
        commentRepository.deleteById(id);
    }

    /**
     * 查询所有评论
     * @return
     */
    @Override
    public List<Comment> findCommentList() {
        return commentRepository.findAll();
    }

    /**
     * 根据id查询评论
     * @param id
     * @return
     */
    @Override
    public Comment findCommentById(String id) {
        return commentRepository.findById(id).get();
    }

    /**
     * 根据父id，查询子评论的分页列表
     * @param parentid
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Comment> findCommentListPageByParentId(String parentid, int page, int size) {
        return commentRepository.findByParentid(parentid, PageRequest.of(page - 1, size));
    }

//    /**
//     * 点赞-效率低
//     * @param id
//     */
//    @Override
//    public void updateCommentThumbupToIncrementingOld(String id) {
//        Comment comment = commentRepository.findById(id).get();
//        comment.setLikenum(comment.getLikenum() + 1);
//        commentRepository.save(comment);
//    }

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 点赞-效率低
     * @param id
     */
    @Override
    public void updateCommentLikenum(String id) {
        // 查询对象
        Query query = Query.query(Criteria.where("_id").is(id));
        // 更新对象
        Update update = new Update();

        update.inc("likenum");

        mongoTemplate.updateFirst(query, update, "comment");
    }

}
